﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ProjectManageSystemApi.Models;
using System.Threading.Tasks;

namespace ProjectManageSystemApi
{
    public class ExceptionFilter : IExceptionFilter
    {
        readonly ILogger<ExceptionFilter> _logger;
        public ExceptionFilter(ILogger<ExceptionFilter> logger) 
        {
            _logger = logger;
        }
        public void OnException(ExceptionContext context)
        {
            if (!context.ExceptionHandled)
            {
                context.Result = new ContentResult
                {
                    Content = JsonConvert.SerializeObject(
                        ApiResultStatus.Fail(ApiResultCodes.OPERATION_FAILED)),
                    StatusCode = StatusCodes.Status200OK,
                    ContentType = "application/json"
                };
            }
            context.ExceptionHandled = true;
            _logger.LogError($"ExceptionFilter：{context.Exception.Message}");
        }

        /// <summary>
        /// 异步发生异常时进入
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task OnExceptionAsync(ExceptionContext context)
        {
            OnException(context);
            return Task.CompletedTask;
        }

    }
}
